<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true" class="mb-4">
      <!-- 编码 Filter -->
      <el-form-item label="编码">
        <el-input
          v-model="queryConditions.code"
          style="width: 200px"
          size="large"
          placeholder="请输入编码"
          clearable
        />
      </el-form-item>

      <!-- 状态 Filter -->
      <el-form-item label="状态">
        <el-select v-model="queryConditions.status" placeholder="请选择状态" style="width: 160px" size="large" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>

      <!-- 单据日期 Filter -->
      <el-form-item label="单据日期：">
        <el-date-picker
            v-model="queryConditions.dateRange"
            type="daterange"
            range-separator="至"
            :start-placeholder="queryConditions.dateRange[0] || '开始'"
            :end-placeholder="queryConditions.dateRange[1] || '结束'"
          />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="fetchData(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表组件 -->
    <TestPage
      :table-data="tableData"
      :columns="tableColumns"
      :current-page="pageNo"
      :total="total"
      :page-size="pageSize"
      @page-change="handlePageChange"
      @action="handleTableAction"
      @edit="openEditDialog"
      @delete="handleDelete"
      @row-audit="handleRowAudit"
    />
  </div>

     <!-- 审核对话框 -->
    <el-dialog
        v-model="auditDialogVisible"
        title="单据审核"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="code">
          <el-input
              v-model="auditForm.code"
              disabled
              placeholder="系统自动填充"
          />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
          <el-select
              v-model="auditForm.auditor"
              placeholder="请选择审核人"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name} `"
                :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
          <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
          <el-select
              v-model="auditForm.checkRes"
              placeholder="请选择审核结果"
              style="width: 100%"
          >
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>

</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import request from '@/util/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import TestPage from '@/test/TestPage.vue'
import { useRouter } from 'vue-router'
import type {User} from "@/types/rs/User.ts";
import type { ProCombine } from '@/types/kc/CPZZ'
import type { OutStoreOrder, outStoreDetail } from '@/types/kc/outStore'
import type { InStoreOrder, InStoreDetail } from '@/types/kc/InStore'

// 分页与查询状态
const pageNo = ref(1)
const pageSize = ref(5)
const total = ref(0)
const list = ref<ProCombine[]>([])
interface QueryConditions {
  code: string
  status: string | null
  dateRange: [string, string] | []
}
const queryConditions = reactive<QueryConditions>({
  code: '',
  status: null,
  dateRange: []
})

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

// 列配置
const tableColumns = ref([
  { prop: 'id', label: 'ID' },
  { prop: 'code', label: '编码' },
  { prop: 'bname', label: 'BOM名称' },
  { prop: 'pname', label: '产品名称' },
  { prop: 'count', label: '数量' },
  { prop: 'uname', label: '业务员' },
  { prop: 'dname', label: '业务部门' },
  { prop: 'skname', label: '仓管人' },
  { prop: 'status', label: '状态' },
  { prop: 'delFlag', label: '删除状态' },
  { prop: 'date', label: '日期' },
  { prop: 'createDate', label: '创建日期' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新日期' },
  { prop: 'updateUser', label: '更新人' }
])

// 审核弹窗
const auditDialogVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({
  code: '',
  auditor: '',
  comment: '',
  checkRes: null
});
const auditRules = reactive({
  pass: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
})
let currentRow: ProCombine | null = null

// 表格数据
const tableData = ref<ProCombine[]>([])

const formatDate = (date: Date, isEndDate: boolean = false) => {
  const pad = (num: number) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1)
  const day = pad(date.getDate())
  if (isEndDate) {
    return `${year}-${month}-${day} 23:59:59`
  }
  return `${year}-${month}-${day} 00:00:00`
}

async function fetchData(page: number) {
  try {
    const params = new URLSearchParams()
    params.append('pageNow', page.toString())
    params.append('pageSize', pageSize.value.toString())

    if (queryConditions.code) {
      params.append('code', queryConditions.code)
    }
    if (queryConditions.status !== null) {
      params.append('status', queryConditions.status)
    }
    if (queryConditions.dateRange.length === 2) {
      const [startRaw, endRaw] = queryConditions.dateRange
      const startDateObj = new Date(startRaw)
      const endDateObj = new Date(endRaw)
      const start = formatDate(startDateObj, false)
      const end = formatDate(endDateObj, true)
      params.append('startDate', start)
      params.append('endDate', end)
    }

    const resp = await request.post(
      'kc/proCombine/getProCombinePage',
      params,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    const d = resp.data.data
    tableData.value = d.list || []
    total.value = d.total || 0
    pageNo.value = d.pageNo || page
  } catch (error) {
    ElMessage.error('获取产品组装数据失败')
    console.error(error)
    tableData.value = []
    total.value = 0
  }
}

// 分页变化
function handlePageChange(newPage: number) {
  fetchData(newPage)
}

// 操作按钮
function handleTableAction(actionName: string) {
  if (actionName === 'add') {
    router.push({ name: 'Addcpzz' })
  }
}

// 重置条件
function reset() {
  queryConditions.code = ''
  queryConditions.status = null
  queryConditions.dateRange = []
  fetchData(1)
}

// 编辑 & 删除
const router = useRouter()

function openEditDialog(row: ProCombine) {
  router.push({ name: 'EditCPZZ', params: { code: row.code } })
}

async function handleDelete(row: ProCombine) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该条记录吗？此操作不可恢复！',
      '警告',
      { type: 'warning' }
    )
    await request.post(
      'kc/proCombine/delProCombine',
      new URLSearchParams({ code: row.code }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    ElMessage.success('删除成功')
    fetchData(pageNo.value)
  } catch (err) {
    if (err === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败')
      console.error(err)
    }
  }
}

// 审核方法
const handleRowAudit = (row: any) => {
  auditForm.code = row.code
  auditDialogVisible.value = true
  console.log('当前审核单据:', row.code)
}

// 提交审核并生成入出库
async function submitAudit() {
  await auditFormRef.value.validate()
  // 审核接口
  const response =await request.post(
    'kc/proCombine/check',
    {
      code: auditForm.code,
      typeId: 2,
      status: 3,
      checkManId: auditForm.auditor,  // 绑定审核人ID
      checkComment: auditForm.comment, // 绑定审批意见
      checkRes: auditForm.checkRes // 绑定审核结果
    }
  )
  ElMessage.success('审核完成')
   ElMessage.success(response.data.message);
    auditDialogVisible.value = false;
    fetchData(pageNo.value); // 刷新表格数据

    // // 拉取单据详情
    
    // const det = await request.get('kc/proCombine/getOneProCombine', { params: { code: auditForm.code } })
    // console.log(det.data.data.status)
    // const data = det.data.data as ProCombine
    // console.log(data)
    // const { inOrder, inDetails, outOrder, outDetails } = transformData(data)

    // // 产品入库
    // await request.post('kc/inStore/addInStore', inOrder)
    // await Promise.all(inDetails.map(d => request.post('kc/inStoreDetail/addInStoreDetail', d)))
    // inDetails.forEach(item =>
    //   request.post('kc/StoreGoodSummary/method', {
    //     sid: item.storeId,
    //     gid: item.goodId,
    //     stock: item.count,
    //     sumCost: item.inStoreSumCost
    //   })
    // )
    // request.post('workflowDesign/workFlow/startProcess', { code: inOrder.inStoreCode, type: 5 })

    // // 原料出库
    // await request.post('kc/outStore/addOutStore', outOrder)
    // await Promise.all(outDetails.map(d => request.post('kc/outStoreDetail/addOutStoreDetail', d)))
    // outDetails.forEach(item =>
    //   request.post('kc/StoreGoodSummary/method', {
    //     sid: item.storeId,
    //     gid: item.goodId,
    //     stock: -item.count,
    //     sumCost: item.outStoreSumCost
    //   })
    // )
    // request.post('workflowDesign/workFlow/startProcess', { code: outOrder.code, type: 6 })

    // ElMessage.success('生成入出库单成功')

  fetchData(1)
}


// /**
//  * 把 ProCombine 转成：
//  *  - 产品入库单头 + 明细 （bom.product）
//  *  - 原料出库单头 + 明细 （bom.material.slice(1...)）
//  */
// function transformData(data: ProCombine) {
//   // --- 1. 产品入库 ---
//   const prod = data.bom.product
//   const prodCount = data.count
//   const inOrder: InStoreOrder = {
//     id: 0,
//     inStoreCode: data.code,
//     goodId: prod.id,
//     goodsCode: prod.code,
//     goodsName: prod.name,
//     count: prodCount,
//     notes: '',
//     storeId: data.sids[0],        // 第一个仓库给成品
//     storeName: '',
//     taxSumPrice: prod.tax * prodCount,
//     sumPrice: prod.tax * prodCount,
//     inStoreSingleCost: prod.tax,
//     inStoreSumCost: prod.tax * prodCount,
//     isDelete: 0,
//     createId: 0,
//     createDate: new Date(),
//     updateId: 0,
//     updateDate: new Date()
//   }
//   // 明细里只要这一条
//   const inDetails: InStoreDetail[] = [{ ...inOrder }]

//   // --- 2. 原料出库 ---
//   const outOrder: OutStoreOrder = {
//     id: 0,
//     code: data.code,
//     orderDate: new Date(data.date),
//     sourceCode: data.code,
//     cid: 0,
//     businessmanId: data.uid,
//     deptId: data.did,
//     orderStatus: 0,
//     storeManId: data.skid,
//     orderTypeId: 0,
//     typeId: 6,  // 自定义出库类型
//     outStoreSumPrice: 0,
//     createId: 0,
//     createDate: new Date(),
//     updateId: 0,
//     updateDate: new Date(),
//     isDelete: 0
//   }
//   const outDetails: outStoreDetail[] = data.bom.material.slice(1).map((m, i) => {
//     const cnt = data.count
//     return {
//       id: 0,
//       outStoreCode: data.code,
//       goodId: m.id,
//       goodsCode: m.code,
//       goodsName: m.name,
//       tax: m.tax || 0,
//       count: cnt,
//       notes: '',
//       storeId: data.sids[i + 1] ?? data.sids[0],
//       storeName: '',
//       unit: '',
//       singlePrice: m.tax || 0,
//       taxSinglePrice: m.tax || 0,
//       taxSumPrice: (m.tax || 0) * cnt,
//       sumPrice: (m.tax || 0) * cnt,
//       outStoreSingleCost: m.tax || 0,
//       outStoreSumCost: (m.tax || 0) * cnt,
//       isDelete: 0,
//       createId: 0,
//       createDate: new Date(),
//       updateId: 0,
//       updateDate: new Date()
//     }
//   })
//   // 合计
//   outOrder.outStoreSumPrice = outDetails.reduce((sum, d) => sum + d.outStoreSumCost, 0)

//   return { inOrder, inDetails, outOrder, outDetails }
// }


// 首次加载
fetchData(1)
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>